package com.momoauth.api_client.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.momoauth.api_client.entity.MoMo_Dist_Item;
import com.momoauth.api_client.entity.MoMo_Dist_Type;
import com.momoauth.api_client.mapper.DistItemMapper;
import com.momoauth.api_client.mapper.DistTypeMapper;
import com.momoauth.api_client.utils.RedisUtil;
import com.momoauth.common.core.result.ResponseResurt;
import com.momoauth.common.security.annotation.RequiresRoles;
import com.momoauth.common.security.enumeration.Logical;
import io.swagger.annotations.Api;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/momo_dist")
@Api(tags = "数据字典")
@RequiresRoles(value = {"超级管理员","普通管理员"}, logical = Logical.OR)
public class DistTypeController {

    @Resource
    DistTypeMapper distTypeMapper;

    @Resource
    DistItemMapper distItemMapper;

    @Resource
    RedisUtil redisUtil;

    /**
     * 数据字典列表
     * @param dist_type
     * @return
     */
    @RequestMapping(value = "/getDistTypeList", method = RequestMethod.GET)
    public ResponseResurt getDistTypeList(MoMo_Dist_Type dist_type) {
        QueryWrapper<MoMo_Dist_Type> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id"); //按主键倒序排序
        Page<MoMo_Dist_Type> page = new Page<>(dist_type.getCurrentPage(), dist_type.getPageSize());
        page.setRecords(distTypeMapper.getDistTypeList(page, queryWrapper));
        return ResponseResurt.success().data(page);
    }

    /**
     * 创建字典
     * @param dist_type
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/createDistType", method = RequestMethod.POST)
    public ResponseResurt createDistType(
            @Validated MoMo_Dist_Type dist_type,
            BindingResult bindingResult
    ) {
        // 非法参数验证
        if (bindingResult.hasErrors()) {
            String errorMsg = bindingResult.getFieldError().getDefaultMessage();
            return ResponseResurt.error().msg(errorMsg);
        }
        // 判断是否存在重复的编号
        Integer isExist = distTypeMapper.existDistTypeCode(dist_type.getCode());
        if (isExist != null) {
            return ResponseResurt.error().msg("很抱歉，已存在相同编号。");
        }
        // 执行新增操作
        int isInsert = distTypeMapper.insert(dist_type);
        if (isInsert > 0) {
            return ResponseResurt.success().msg("恭喜您，创建成功。");
        }
        return ResponseResurt.error().msg("很抱歉，创建失败！");
    }

    /**
     * 修改字典
     * @param dist_type
     * @param bindingResult
     * @return
     */
    @RequestMapping(value = "/updateDistType", method = RequestMethod.GET)
    public ResponseResurt updateDistType(
            @Validated MoMo_Dist_Type dist_type,
            BindingResult bindingResult
    ) {
        // 非法参数验证
        if (bindingResult.hasErrors()) {
            String errorMsg = bindingResult.getFieldError().getDefaultMessage();
            return ResponseResurt.error().msg(errorMsg);
        }
        // 执行更新操作
        int isUpdate = distTypeMapper.updateById(dist_type);
        if (isUpdate > 0) {
            return ResponseResurt.success().msg("恭喜您，修改成功。");
        }
        return ResponseResurt.error().msg("很抱歉，修改失败！");
    }

    /**
     * 字典详情
     * @param dist_type
     * @return
     */
    @RequestMapping(value = "/getDistTypeById", method = RequestMethod.GET)
    public ResponseResurt getDistTypeById(MoMo_Dist_Type dist_type) {
        dist_type = distTypeMapper.selectById(dist_type.getId());
        return ResponseResurt.success().data(dist_type);
    }

    /**
     * 删除字典
     * @param dist_type
     * @return
     */
    @RequestMapping(value = "/deleteDistType", method = RequestMethod.GET)
    public ResponseResurt deleteDistType(MoMo_Dist_Type dist_type) {
        // 判断是否有字典项使用了该编号
        Integer isExist = distItemMapper.existDistItemById(dist_type.getId());
        if (isExist != null) {
            return ResponseResurt.error().msg("该字典下存在字典项，无法删除。");
        }
        // 执行删除操作（物理删除）
        int isDelete = distTypeMapper.deleteById(dist_type.getId());
        if (isDelete > 0) {
            // 同时删除缓存
            if (redisUtil.hasKey(String.valueOf(dist_type.getId()))) {
                redisUtil.del(String.valueOf(dist_type.getId()));
            }
            return ResponseResurt.success().msg("恭喜您，删除成功。");
        }
        return ResponseResurt.error().msg("很抱歉，删除失败！");
    }

    /**
     * 缓存数据
     * @param list
     * @return
     */
    @RequestMapping(value = "/cacheData", method = RequestMethod.POST)
    public ResponseResurt cacheData(String list) {
        ArrayList<MoMo_Dist_Type> distTypeArrayList  = JSON.parseObject(
                list, new TypeReference<ArrayList<MoMo_Dist_Type>>(){});
        ArrayList<MoMo_Dist_Item> distItemArrayList; //初始化
        for (MoMo_Dist_Type dist_type : distTypeArrayList) {
            // 根据字典编码查询所有字典项
            distItemArrayList = distItemMapper.getAllDistItemByCode(dist_type.getCode());
            if (distItemArrayList.size() > 0) {
                // 缓存数据
                redisUtil.set(String.valueOf(dist_type.getId()), distItemArrayList);
            }
        }
        return ResponseResurt.success().msg("缓存成功");
    }
}
